package cn.itcast.www.utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * 该类为动态创建一个指定类型的数组，不用强制类型转换
 * @author:LZH
 * @time:2016年1月28日
 */
public class ArrayMaker<T>{
	private Class<T> type;

	public ArrayMaker(Class<T> type) {
		this.type = type; // 为何要传入呢？因为我们在本方法中不能直接获取到T.class类型，也不能通过反射获取到本类
	}

	@SuppressWarnings("unchecked")
	T[] createArray(int size) {
		type = (Class<T>) this.getClass().getComponentType();
		return (T[]) Array.newInstance(type, size);
	}

	List<T> createList() {
		return new ArrayList<T>();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * Even though kind is stored as Class<T> , erasure means that it is
		 * actually just being stored as a Class, with no parameter. So, when
		 * you do some thing with it, as in creating an array,
		 * Array.newInstance( ) doesn’t actually have the type information
		 * that’s implied in kind; so it cannot produce the specific result,
		 * which must therefore be cast, which produces a warning that you
		 * cannot satisfy.
		 */
		ArrayMaker<TypeDemo> am2 = new ArrayMaker<TypeDemo>(TypeDemo.class);
		System.out.println(Arrays.asList(am2.createArray(10)));
		System.out.println(Arrays.asList(am2.createList()));
	}

}

class TypeDemo {
	@Override
	public String toString() {
		return "type";
	}
}